import { useCallback, useEffect, useRef } from "react";

/**
 * 监听元素尺寸变化
 *
 * @param {Function} onCallBack 回调函数
 * @returns {[Ref]} targetRef
 */
const useResizeObserver = (onCallBack) => {
  const targetRef = useRef(null);

  const handle = useCallback((...arg) => onCallBack && onCallBack(...arg), [onCallBack]);

  const createObserver = useCallback(() => {
    const resizeObserver = new ResizeObserver(handle);
    const target = targetRef.current;
    target && resizeObserver.observe(target);
    return () => resizeObserver.unobserve(target);
  }, [targetRef, handle]);

  useEffect(() => createObserver(), [createObserver]);

  return [targetRef];
};

export default useResizeObserver;
